package com.tj.api.aop;

import com.fqgj.log.util.Constants;
import com.robert.vesta.util.IdUtils;
import com.tj.api.rest.TestController;
import org.apache.logging.log4j.ThreadContext;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * task 生成traceId
 * Created with IntelliJ IDEA.
 * User: binary
 * Date: 2019/01/02
 * Time: 下午3:47
 */
@Aspect
@Component
@Order(Integer.MAX_VALUE)
public class TaskTraceIdAop {

    private static final Logger LOGGER = LoggerFactory.getLogger(TestController.class);

    @Around("execution(public * com.tj.api.task..*.*(..))")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        //获取类的字节码对象，通过字节码对象获取方法信息
        Class<?> targetCls = joinPoint.getTarget().getClass();
        //获取方法签名(通过此签名获取目标方法信息)
        MethodSignature ms = (MethodSignature) joinPoint.getSignature();
        //获取目标方法上的注解指定的操作名称
        Method targetMethod = targetCls.getDeclaredMethod(ms.getName(), ms.getParameterTypes());
        Scheduled scheduled = targetMethod.getAnnotation(Scheduled.class);

        if (scheduled != null) {
            ThreadContext.put(Constants.TRACE_ID, IdUtils.genId() + "");
            LOGGER.info("任务被触发,name:{}", targetMethod.getName());
        }

        Object[] args = joinPoint.getArgs();
        Object resultObj = null;
        try {
            resultObj = joinPoint.proceed(args);
            return resultObj;
        } catch (Exception e) {
            throw e;
        } finally {
            ThreadContext.clearAll();
        }
    }

}
